# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         utils.py
# Description:
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2019/11/18 17:32
# -------------------------------------------------------------------------------
import logging
import re

from apps.HttpAutoTestService.core.parser import regex_replace_variables, regex_replace_functions

logger = logging.getLogger(__name__)

# 绝对http url正则表达式
absolute_http_url_regexp = re.compile(r"^https?://", re.I)


def build_url(base_url, url):
    """
    构建URL
    在url前面加上主机名，除非它已经是一个绝对url
    :param base_url:
    :param url:
    :return:
    """
    if absolute_http_url_regexp.match(url):
        return url
    elif base_url:
        return "{}/{}".format(base_url.rstrip("/"), url.lstrip("/"))
    else:
        logger.error("base url 缺失!")


def ensure_mapping_format(variables):
    """
    确认variables是mapping格式
    :param variables: 原始参数
    :return:确定格式为dict的参数variables
    """
    if isinstance(variables, list):
        variables_dict = {}
        for map_dict in variables:
            if isinstance(map_dict, dict):
                variables_dict.update(map_dict)
            else:
                logger.error("参数格式错误！")
        return variables_dict
    elif isinstance(variables, dict):
        return variables
    elif isinstance(variables, str):
        variables = eval(variables)
        if isinstance(variables, (dict, list)):
            return ensure_mapping_format(variables)
        else:
            logger.error("参数格式错误！")
    else:
        logger.error("参数格式错误！")


def parse_request_args(content, variables_mapping):
    '''
    http请求参数解析
    :param content:待解析内容
    :param variables_mapping:
    :return:
    '''
    content = regex_replace_variables(content=content, variables_mapping=variables_mapping)
    content = regex_replace_functions(content=content)
    return content


def parse_ext_method_args(content, variables_mapping):
    '''
    扩展方法参数解析
    :param content:
    :param variables_mapping:
    :return:
    '''
    return parse_request_args(content, variables_mapping)
